/**
 * 收银系统socket 服务
 * Created by shc@lierda.com on 2017/5/7.
 */
var net = require('net');
var DB =  require('../web/db/db');
var Cashier =  require('../web/routes/cashier');
var socketPort = 9999;

exports.cashierSocketstart = startSocket;
function startSocket(){
    var server = net.createServer(function(socket) {
        var devip = socket.remoteAddress;
        if(devip){
            console.log(devip+":connected");
        }
        var devport = socket.remotePort;
        socket.setTimeout(1000 * 60*60*12, function () {
            console.log("timeout server close connect");
        });
        var _ddcmac = null;
        socket.on('data', function (data) {
            var newStr= data.toString();
            doData(socket,newStr)
        });
        socket.on('end', function () {
            console.log("end");
        });
        socket.on('timeout', function (data) {
            console.log("timeout");
            socket.end();
        });
        socket.on('error', function (data) {
            console.log("error");
        });
        socket.on('close', function (data) {
            console.log("close");
        });
    }).listen(socketPort);
    console.log("Server start on :" + socketPort);
}
/*处理请求数据*/
function doData(socket,data){
    var msg = {
        success:false
    };
   console.log("socket:"+data);
   if(data){
       try{
           var json = JSON.parse(data);

           if(!json["cashierId"]){
               msg["msg"]="缺少收银机id";
               socket.write(JSON.stringify(msg));
               return;
           }
           if(!json["token"]){
               msg["msg"]="缺少token";
               socket.write(JSON.stringify(msg));
               return;
           }
           if(!json["operation"]){
               msg["msg"]="缺少操作命令";
               socket.write(JSON.stringify(msg));
               return;
           }
           if(!json["stamp"]){
               msg["msg"]="缺少时间戳";
               socket.write(JSON.stringify(msg));
               return;
           }
           var msg={success:false,stamp:json.stamp,msg:""};
           if(json["operation"]=="vipRegister"){
               if(!json["shopId"]){
                   msg["msg"]="缺少店铺id";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["idcard"]){
                   msg["msg"]="缺少身份证";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["phone"]){
                   msg["msg"]="缺少手机号";
                   socket.write(JSON.stringify(msg));
                   return;
               }
                vipRegister(socket,json,msg);
           }
           if(json["operation"]=="vipSearch"){
               if(!json["shopId"]){
                   msg["msg"]="缺少店铺id";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["phone"]){
                   msg["msg"]="缺少手机号";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               vipSearch(socket,json,msg);
           }
           if(json["operation"]=="getShopGoods"){
               if(!json["shopId"]){
                   msg["msg"]="缺少店铺id";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               getShopGoods(socket,json,msg);}
           if(json["operation"]=="uploadOrder"){
               if(!json["shopId"]){
                   msg["msg"]="缺少店铺id";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["user_id"]){
                   msg["msg"]="缺少用户名称";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["order_sn"]){
                   msg["msg"]="缺少订单编号";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["consignee"]){
                   msg["msg"]="缺少收货人名称";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["postcard"]){
                   msg["msg"]="缺少身份证号（收货人）";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["country"]){
                   msg["msg"]="缺少收货人国家";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["province"]){
                   msg["msg"]="缺少收货人省份";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["city"]){
                   msg["msg"]="缺少收货人城市";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["district"]){
                   msg["msg"]="缺少收货人地区";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["address"]){
                   msg["msg"]="缺少收货人详细地址";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["zipcode"]){
                   msg["msg"]="缺少收货人邮编";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["mobile"]){
                   msg["msg"]="缺少收货人手机";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["goods_amount"]){
                   msg["msg"]="缺少商品总金额";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["shipping_fee"]){
                   msg["msg"]="缺少配送费用";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["insure_fee"]){
                   msg["msg"]="缺少商品保费";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["money_paid"]){
                   msg["msg"]="缺少已付款金额";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["order_amount"]){
                   msg["msg"]="缺少订单总金额";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["pay_time"]){
                   msg["msg"]="缺少支付时间";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["goods_tax"]){
                   msg["msg"]="缺少订单关税";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["warehouse_op_fee"]){
                   msg["msg"]="缺少仓储综合操作费";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["pay_trade_no"]){
                   msg["msg"]="缺少交易平台交易流水号";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["add_time"]){
                   msg["msg"]="缺少下单时间";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["discount"]){
                   msg["msg"]="缺少非现金抵扣金额";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               if(!json["goods"]){
                   msg["msg"]="缺少商品信息";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               uploadOrder(socket,json,msg);
           }
           if(json["operation"]=="nonpaymentOrderByUserId") {
               if(!json["idcard"] && !json["phone"] ){
                   msg["msg"]="缺少会员信息IDphone";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               nonpaymentOrderByUserId(socket, json, msg);
           }
           if(json["operation"]=="getGoodsByOrderId") {
               if (!json["order_id"]) {
                   msg["msg"] = "缺少订单ID";
                   socket.write(JSON.stringify(msg));
                   return;
               }
               getGoodsByOrderId(socket,json,msg);
           }
       }catch (e){
           console.log(e);
           msg["msg"]="提交格式有误";
           socket.write(JSON.stringify(msg));
       }
   }else{
       msg["msg"]="提交格式有误";
       socket.write(JSON.stringify(msg));
   }
}

/**注册*/
function vipRegister(socket,json,msg){
    Cashier.vipSearch(json.phone,function(data,flag){
        if(flag){
            msg["success"] = true;
            msg["msg"] = "该用户信息已存在,返回信息成功";
            msg["user"] = data.user;
            msg["address"] = data.address;
            socket.write(JSON.stringify(msg));
        }else{
            Cashier.vipRegister(json.phone,json.idcard,function(d,f1){
                if(f1){
                    msg["success"] = true;
                    msg["msg"] = "注册成功";
                    msg["user"] = d.user;
                    msg["address"] = d.address;
                }else{
                    msg["msg"] = "注册失败";
                }
                socket.write(JSON.stringify(msg));
            });
        }
    });
}
/*查询*/
function vipSearch(socket,json,msg){
    Cashier.vipSearch(json.phone,function(data,flag){
        console.log(JSON.stringify(data));
        if(flag){
            msg["success"] = true;
            msg["msg"] = "查询成功";
            msg["user"] = data.user;
            msg["address"] = data.address;
        }else{
            msg["msg"] = "查询失败";
        }
        socket.write(JSON.stringify(msg));
    });
}
/**获取店铺商品信息*/
function getShopGoods(socket,json,msg){
    Cashier.getShopGoods(json.shopId,function(data,flag){
        if(flag){
            msg["success"] = true;
            msg["msg"] = "查询成功";
            msg["goods"] = data.goods;
        }else{
            msg["msg"] = "查询失败";
        }
        socket.write(JSON.stringify(msg));
    });
}

/**付款订单信息*/
function uploadOrder(socket,json,msg){
    Cashier.uploadOrder(json.order_sn, json.user_id, json.consignee, json.country, json.province, json.city, json.district, json.address, json.zipcode, json.mobile, json.goods_amount, json.shipping_fee, json.insure_fee, json.money_paid, json.orderTotalAmount, json.pay_time, json.goods_tax, json.warehouse_op_fee, json.postcard, json.pay_trade_no, json.shopId, json.add_time, json.discount, json.goods,function(flag){
        if(flag){
            msg["success"] = true;
            msg["msg"] = "发送成功";
        }else{
            msg["msg"] = "goods_id不能为空";
        }
        socket.write(JSON.stringify(msg));
    });
}
//通过会员idcard、phone查未付款订单列表
function nonpaymentOrderByUserId(socket,json,msg){
    Cashier.nonpaymentOrderByUserId(json.idcard,json.phone,function(data,flag){
        if(flag){
            msg["success"] = true;
            msg["msg"] = "查询未付款订单成功";
            msg["data"] = {
                cashierId : json["cashierId"],
                token : json["token"],
                stamp :  json["stamp"] ,
            };
            msg["orders"] = data.orders;
        }else{
            msg["msg"] = "请求失败:用户信息有误";
        }
        socket.write(JSON.stringify(msg));
    });
}
////根据订单orderID取商品列表
function getGoodsByOrderId(socket,json,msg){
    Cashier.getGoodsByOrderId(json.order_id,function(data,flag){
        if(flag){
            msg["success"] = true;
            msg["msg"] = "查询成功";
            msg["goods"] = data.goods;
        }else{
            msg["msg"] = "请求失败:订单ID有误";
        }
        socket.write(JSON.stringify(msg));
    });
}